﻿using AssetManegement.Filter;
using Common;
using IService;
using IService.SystemTableService;
using Microsoft.AspNetCore.Mvc;
using Minio.DataModel;
using Model.Models;
using ModelDto;
using ModelDto.Request;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace AssetManegement.Controllers
{
    /// <summary>
    /// 在线聊天接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [ServiceFilter(typeof(MyTokenFilterAttribute))]
    public class OnLineController : ControllerBase
    {
        private readonly ILogger<OnLineController> _logger;

        private readonly IAccountService _AccountService;
        private readonly IOnLineMsgService _onLineMsgService;



        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="AccountService"></param>
        /// <param name="onLineMsgService"></param>
        public OnLineController(ILogger<OnLineController> logger, IAccountService AccountService, IOnLineMsgService onLineMsgService)
        {
            _logger = logger;
            _AccountService = AccountService;
            _onLineMsgService = onLineMsgService;
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetUserList(KeyWordsRequest request)
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            List<AccountResponse> list = new List<AccountResponse>();
            var resList = await _AccountService.GetListCacheAsync();
            resList = resList.Where(a => a.Id != "xitongguanliyuan" && a.Id != CurrentUser.Account.Id).ToList();
            if (!string.IsNullOrWhiteSpace(request.KeyWords))
            {
                resList = resList.Where(a => a.Name.Contains(request.KeyWords) || a.AccountNo.Contains(request.KeyWords)).ToList();
            }



            if (resList != null && resList.Count > 0)
            {

                var ids = resList.Select(a => a.Id).ToList();
                var msgList = await _onLineMsgService.GetUserMsgFirstList(new DeleteMoreRequest() { IdArry = ids }, CurrentUser.Account);
                foreach (var item in resList)
                {
                    list.Add(EntityMapperHelper.Mapper<AccountResponse, Account>(item));
                }

                if (msgList != null && msgList.Any())
                {
                    foreach (var item in list)
                    {
                        var temp = msgList.Where(a => a.UserId == item.Id).FirstOrDefault();
                        item.Msg = temp?.Msg ?? "";
                        item.Time = temp?.Time ?? "";
                    }
                }
            }


            return response.Sucess(list);
        }

        /// <summary>
        /// 获取聊天记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetOnLineMsgList(DelRequest request)
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            var list = await _onLineMsgService.GetOnLineMsgList(request, CurrentUser.Account);

            return response.Sucess(list);
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> SendMsg(SendMsgRequest request)
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            (bool success,string msg) = await _onLineMsgService.SendMsg(request, CurrentUser.Account);

            if (success)
            {
                return response.Sucess(msg, msg);
            }
            return response.Fail(msg);
        }
        
    }
}
